# -*- encoding:utf-8 -*-
# @Time: 2022/10/26 21:46
# @Author : moran
# @Email: moran@maqu.com
# @File: permission.py
# @Software: PyCharm
from functools import update_wrapper

from rest_framework.permissions import BasePermission
from django.contrib.auth.models import Group
from rest_framework.response import Response


class TeacherPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user  # 获取到当前发送请求的用户信息
        # 判断身份，查询用户是不是在老师分组
        gourp = Group.objects.filter(name='老师').first()
        user_groups = user.groups.all()
        return user.is_superuser or gourp in user_groups


class ActiveUserPermission(BasePermission):
    def has_permission(self, request, view):
        # 操作的用户必须是当前登录的用户
        user = request.user
        return user.id == int(view.kwargs['pk'])


class ActiveUserPPermission(BasePermission):
    def has_permission(self, request, view):
        # 操作的用户必须是当前登录的用户
        user = request.user
        return user.id == int(request.data.get('user'))


# 更改权限装饰器
def wrap_permission(*permissions, validate_permission=True):
    def decorator(func):
        def wrapper(self, request, *args, **kwargs):
            self.permission_classes = permissions
            if validate_permission:
                self.check_permissions(request)
            return func(self, request, *args, **kwargs)
        return update_wrapper(wrapper, func)
    return decorator


def auto_user(func):
    def wrapper(self, request, *args, **kwargs):
        request.POST._mutable = True  # 让请求参数可以进行修改
        request.data['user'] = request.user.id

        return func(self, request, *args, **kwargs)
    return wrapper


class RootPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user
        return user.is_superuser


def update_auto_user(func):
    def wrapper(self, request, *args, **kwargs):
        # 判断当前操作的用户是不是这个数据的创建者
        # 设：文章的id为3,作者的id为1,当前登录用户id为5
        # 所有的没有被逻辑删除的文章数据集里面的id等于1，并且user用户为5
        res = self.get_queryset().filter(id=kwargs['pk'], user=request.user)
        if not res:
            return Response({'detail': '您没有修改的权限'})
        # 修改不可以更改作者，只能是当前登录的用户
        request.POST._mutable = True
        request.data['user'] = request.user.id
        return func(self, request, *args, **kwargs)
    return wrapper


def destroy_auto_user(func):
    def wrapper(self, request, *args, **kwargs):
        res = self.get_queryset().filter(id=kwargs['pk'], user=request.user)
        if not res:
            return Response({'detail': '您没有删除的权限'})
        return func(self, request, *args, **kwargs)
    return wrapper
